package fr.umlv.m2.jee.spij.service.authentification;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;


@Service
public class ResourcesUtils {

    public static final String DATE_FORMAT_KEY = "dateformat.default";

    private static final Log logger = LogFactory.getLog(ResourcesUtils.class);

    private final MessageSource messageSource;

    @Autowired
    public ResourcesUtils(MessageSource ms) {
        messageSource = ms;
    }

    /**
     * Return the property value for the contextual locale. If no value is
     * found, the passed key is returned.
     */
    public String getProperty(String key) {
        if (key == null) {
            return "";
        }
        return messageSource.getMessage(key, null, LocaleContextHolder
                .getLocale());
    }

    /**
     * Return the date as a localized string using the contextual locale.
     */
    public String getFormattedDate(Date date) {
        if (date == null) {
            return "";
        }
        String format = getProperty(DATE_FORMAT_KEY);
        SimpleDateFormat dateFormat = new SimpleDateFormat(format);
        return dateFormat.format(date);
    }

    /**
     * Spring resources loader uses as default the file encoding used by the OS.
     * To simplify the configuration you can enforce the default file encoding
     * to UTF-8.
     */
    public void forceFileEncodingToUTF8() {
        if (!"UTF-8".equals(System.getProperty("file.encoding"))) {
            try {
                if (logger.isWarnEnabled()) {
                    logger
                            .info("Forcing file.encoding system property to UTF-8 instead of "
                                    + System.getProperty("file.encoding"));
                }

                System.setProperty("file.encoding", "UTF-8");
            } catch (Exception e) {
                if (logger.isWarnEnabled()) {
                    logger
                            .warn(
                                    "Could not set file.encoding programmatically to UTF-8, please configure the JVM manually",
                                    e);
                }
            }
        }
    }
}
